"""
设备管理API序列化器
"""
from rest_framework import serializers
from .models import Device, DeviceBrand, DeviceType, PlatformCredential, DeviceCommand


class DeviceBrandSerializer(serializers.ModelSerializer):
    """设备品牌序列化器"""
    device_count = serializers.SerializerMethodField()
    
    class Meta:
        model = DeviceBrand
        fields = ['id', 'name', 'api_endpoint', 'auth_type', 'logo', 'description',
                 'is_active', 'device_count', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']
    
    def get_device_count(self, obj):
        """获取该品牌下的设备数量"""
        return obj.device_set.count()


class DeviceTypeSerializer(serializers.ModelSerializer):
    """设备类型序列化器"""
    device_count = serializers.SerializerMethodField()
    category_display = serializers.CharField(source='get_category_display', read_only=True)
    
    class Meta:
        model = DeviceType
        fields = ['id', 'name', 'category', 'category_display', 'supported_commands', 'icon',
                 'description', 'device_count', 'created_at']
    
    def get_device_count(self, obj):
        """获取该类型下的设备数量"""
        return obj.device_set.count()


class DeviceCommandSerializer(serializers.ModelSerializer):
    """设备命令序列化器"""
    device_name = serializers.CharField(source='device.name', read_only=True)
    user_name = serializers.CharField(source='user.username', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = DeviceCommand
        fields = ['id', 'device', 'device_name', 'user', 'user_name', 'command',
                 'parameters', 'status', 'status_display', 'result', 'error_message',
                 'executed_at', 'created_at']
        read_only_fields = ['user', 'executed_at', 'created_at']
    
    def validate_command(self, value):
        """验证命令格式"""
        if not isinstance(value, dict):
            raise serializers.ValidationError("命令必须是有效的JSON格式")
        return value
    
    def validate_parameters(self, value):
        """验证参数格式"""
        if value and not isinstance(value, dict):
            raise serializers.ValidationError("参数必须是有效的JSON格式")
        return value


class PlatformCredentialSerializer(serializers.ModelSerializer):
    """平台凭证序列化器"""
    brand_name = serializers.CharField(source='brand.name', read_only=True)
    user_name = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = PlatformCredential
        fields = ['id', 'user', 'user_name', 'brand', 'brand_name', 'platform_username',
                 'access_token', 'refresh_token', 'token_expires_at', 'additional_data',
                 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['user', 'created_at', 'updated_at']
        extra_kwargs = {
            'platform_password': {'write_only': True},
        }
    
    def validate_additional_data(self, value):
        """验证附加数据格式"""
        if value and not isinstance(value, dict):
            raise serializers.ValidationError("附加数据必须是有效的JSON格式")
        return value


class DeviceListSerializer(serializers.ModelSerializer):
    """设备列表序列化器"""
    brand_name = serializers.CharField(source='brand.name', read_only=True)
    device_type_name = serializers.CharField(source='device_type.name', read_only=True)
    room_display = serializers.CharField(source='get_room_display', read_only=True)
    connection_status_display = serializers.CharField(source='get_connection_status_display', read_only=True)
    owner_username = serializers.CharField(source='owner.username', read_only=True)
    
    class Meta:
        model = Device
        fields = ['id', 'name', 'brand_name', 'device_type_name', 'device_id',
                 'room', 'room_display', 'connection_status', 'connection_status_display',
                 'owner_username', 'is_active', 'last_seen', 'created_at']


class DeviceDetailSerializer(serializers.ModelSerializer):
    """设备详情序列化器"""
    brand = DeviceBrandSerializer(read_only=True)
    device_type = DeviceTypeSerializer(read_only=True)
    room_display = serializers.CharField(source='get_room_display', read_only=True)
    connection_status_display = serializers.CharField(source='get_connection_status_display', read_only=True)
    owner_username = serializers.CharField(source='owner.username', read_only=True)
    is_online = serializers.BooleanField(read_only=True)
    
    # 写入时使用ID
    brand_id = serializers.IntegerField(write_only=True)
    device_type_id = serializers.IntegerField(write_only=True)
    
    class Meta:
        model = Device
        fields = ['id', 'name', 'brand', 'brand_id', 'device_type', 'device_type_id',
                 'device_id', 'room', 'room_display', 'status', 'connection_status',
                 'connection_status_display', 'last_seen', 'owner_username', 'is_online',
                 'is_active', 'created_at', 'updated_at']
        read_only_fields = ['owner', 'created_at', 'updated_at']
    
    def validate_device_id(self, value):
        """验证设备ID唯一性"""
        if value:
            queryset = Device.objects.filter(device_id=value)
            if self.instance:
                queryset = queryset.exclude(pk=self.instance.pk)
            if queryset.exists():
                raise serializers.ValidationError("该设备ID已存在")
        return value
    
    def create(self, validated_data):
        """创建设备"""
        brand_id = validated_data.pop('brand_id')
        device_type_id = validated_data.pop('device_type_id')
        
        validated_data['brand_id'] = brand_id
        validated_data['device_type_id'] = device_type_id
        validated_data['owner'] = self.context['request'].user
        
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """更新设备"""
        if 'brand_id' in validated_data:
            instance.brand_id = validated_data.pop('brand_id')
        if 'device_type_id' in validated_data:
            instance.device_type_id = validated_data.pop('device_type_id')
        
        return super().update(instance, validated_data)


class DeviceControlSerializer(serializers.Serializer):
    """设备控制序列化器"""
    command_id = serializers.IntegerField(help_text="命令ID")
    parameters = serializers.DictField(required=False, help_text="命令参数")
    
    def validate_command_id(self, value):
        """验证命令ID"""
        try:
            command = DeviceCommand.objects.get(id=value)
            return command
        except DeviceCommand.DoesNotExist:
            raise serializers.ValidationError("指定的命令不存在")


class DeviceStatusSerializer(serializers.Serializer):
    """设备状态序列化器"""
    status = serializers.ChoiceField(choices=Device.STATUS_CHOICES)
    last_seen = serializers.DateTimeField(read_only=True)
    response_time = serializers.FloatField(read_only=True, help_text="响应时间（毫秒）")
    error_message = serializers.CharField(read_only=True, required=False)


class DeviceStatisticsSerializer(serializers.Serializer):
    """设备统计序列化器"""
    total_devices = serializers.IntegerField()
    online_devices = serializers.IntegerField()
    offline_devices = serializers.IntegerField()
    unknown_devices = serializers.IntegerField()
    devices_by_type = serializers.DictField()
    devices_by_brand = serializers.DictField()
    recent_activities = serializers.ListField()